// src/pages/article/index.tsx
import React, { useRef, useState, useEffect,useCallback } from "react";
import Back from "@shared/back";
import GeekIcon from "@shared/geekIcon";
import { FillinOutline } from "antd-mobile-icons";
import { Skeleton } from "antd-mobile";
import styles from "@pages/article/styles/styles.module.less";
import Collect from "@pages/article/widgets/collect";
import Favourite from "@pages/article/widgets/favourite";
import Comment from "@pages/article/widgets/comment";
import Follow from "@pages/article/widgets/follow";
import PublishComment from "@pages/article/widgets/publishComment";
import { useRequestArticleQuery } from "@service/article";
import { useParams } from "react-router-dom";
import dayjs from "dayjs";
import localizedFormat from "dayjs/plugin/localizedFormat";
import "highlight.js/styles/atom-one-dark.css";
//评论列表   
import { useRequestCommentsMutation } from "@service/comment";
import Infinite from "@shared/infinite";
import { commentSelectors,saveComments,clearComments } from "@slice/comment";
import { useTypedSelector } from "@store/index";
import { useDispatch } from "react-redux"; 
dayjs.extend(localizedFormat);
dayjs.extend(localizedFormat);
export default function Article() {
  const dispatch = useDispatch();
  // 获取文章 id
  const id = useParams<{ id: string }>().id!;
  // 发送请求获取文章详情
  const { data, isLoading, isSuccess } = useRequestArticleQuery(id);
  // 获取文章内容区域上面的元素
  const topRef = useRef<HTMLDivElement | null>(null);
  // 获取滚动区域元素
  const articleRef = useRef<HTMLDivElement | null>(null);
  // 用于控制头部作者信息的显示和隐藏
  const [show, setShow] = useState(false);
  // 用于记录是否显示评论区域
  const [showComment, setShowComment] = useState(false);
  // 用于获取评论元素对象
  const commentRef = useRef<HTMLDivElement | null>(null);
  // 检测文章是否获取成功
  useEffect(() => {
    // 如果文章内容没有获取成功, 阻止程序继续运行
    if (!isSuccess) return;
    // 获取滚动区域DOM对象
    const articleElm = articleRef.current!;
    // 获取文章内容区域上面的区域DOM对象
    const topElm = topRef.current!;
    // 滚动事件的事件处理函数
    const scrollHandler = () => {
      // 如果滚动距离大于了内容区域上面元素的高度
      setShow(articleElm.scrollTop > topElm.offsetHeight);
    };
    // 为滚动区域添加滚动事件
    articleElm.addEventListener("scroll", scrollHandler);
    // 清理驱动区域的滚动事件
    return () => articleElm.removeEventListener("scroll", scrollHandler);
  }, [isSuccess]);
  useEffect(() => {
    // 显式评论区域
    if (showComment) {
      articleRef.current!.scrollTo({
        top: commentRef.current?.offsetTop,
        behavior: "smooth",
      });
    } else {
      // 显示内容区域
      articleRef.current!.scrollTo({ top: 0, behavior: "smooth" });
    }
  }, [showComment]);
  // 评论分页偏移量
  const [offset, setOffset] = useState<string | undefined>();
  // 是否有更多评论可以加载
  const [hasMore, setHasMore] = useState(true);
  // 发送请求获取评论列表
  const [requestComments, { data: comments }] = useRequestCommentsMutation();

  // 获取评论列表数据
  const allComments = useTypedSelector(commentSelectors.selectAll);

  // 用于加载评论列表
  const loadMore = useCallback(() => {
    return requestComments({type: "a", source: id, limit: 10, offset})
      .unwrap()
      .then((response) => {
        // 保存评论列表
        dispatch(saveComments(response.data.results));
        // 如果不两者相等说明没有更多数据可以加载
        setHasMore(response.data.end_id !== response.data.last_id);
        // 设置分页偏移量
        setOffset(response.data.last_id);
      });
  }, [dispatch, id, offset, requestComments]);
  // 重置评论列表
  const resetComments = useCallback(() => {
    setOffset(undefined);
    setHasMore(true);
    dispatch(clearComments());
  }, [dispatch]);
  // 组件挂载完成之后先清空本地存储的评论列表
  useEffect(() => {
    dispatch(clearComments());
  }, [dispatch]);
  return (
    <>
      <div className={styles.header}>
        <div className={styles.left}>
          <Back />
          <div className={styles.center}>
          </div>
        </div>
        <GeekIcon type="icongengduo" className={styles.more} />
      </div>
      {/* 修正后的文章内容容器 */}
      <div ref={articleRef} className={styles.article}>
        {isLoading && (
          <div className={styles.skeleton}>
            <Skeleton.Paragraph lineCount={2} animated />
            <Skeleton.Paragraph lineCount={3} animated />
            <Skeleton.Paragraph lineCount={5} animated />
            <Skeleton.Paragraph lineCount={2} animated />
            <Skeleton.Paragraph lineCount={4} animated />
          </div>
        )}
        {isSuccess && (
          <>
            {/* 修正后的文章内容结构 */}
            <div ref={topRef}>
              <h2 className={styles.title}>{data.data.title}</h2>
              <div className={styles.meta}>
                <span>{dayjs(data.data.pubdate).locale("zh-cn").format("LL")}</span>
                <span>{data.data.read_count} 阅读</span>
                <span>{data.data.comm_count} 评论</span>
              </div>
              <div className={styles.author}>
                <div className={styles.avatar}>
                  <img src={data.data.aut_photo} alt="" />
                  <span>{data.data.aut_name}</span>
                </div>
                <Follow isFollow={data?.data.is_followed} userId={data?.data.aut_id} />
              </div>
            </div>

            {/* 文章内容区域 */}
            <div className={styles.content}>
              <div dangerouslySetInnerHTML={{ __html: data.data.content }} />
              <div className={styles.footnote}>
                文章发布于：{dayjs(data.data.pubdate).locale("zh-cn").format("LL")}
              </div>
            </div>

            {/* 评论区域 */}
            <div className={styles.comment} ref={commentRef}>
              {/* 评论组件可在此添加 */}
             
              <h4 className={styles.title}>
            全部评论 ({comments?.data.total_count})
          </h4>
          {allComments.map((comment) => (
            <Comment key={comment.com_id} comment={comment} resetComments={resetComments} />
          ))}
          <Infinite hasMore={hasMore} loadMore={loadMore} />
            </div>
          </>
        )}
      </div>

      {/* 底部操作栏 */}
      <div className={styles.bar}>
      <div className={styles.sofa}>
      <PublishComment id={id} resetComments={resetComments} />
        </div>
        <div className={styles.icons}>
        <div className={styles.item} onClick={() => setShowComment((show) => !show)}>
            <GeekIcon type="iconbtn_comment" />
            <span>评论</span>
          </div>
          <Collect isCollect={data?.data.is_collected} id={data?.data.art_id} />
          <Favourite id={data?.data.art_id} isFavourite={data?.data.attitude === 1} />
          <div className={styles.item}>
            <GeekIcon type={"iconbtn_share"} />
            <span>分享</span>
          </div>
        </div>
      </div>
    </>
  );
}